package com.fysports.web.controller;

import com.google.common.collect.Maps;
import com.jfinal.aop.Clear;
import com.fysports.framework.kit.security.MD5Kit;
import com.fysports.web.kit.commons.CookiesKit;
import com.fysports.web.kit.commons.DateTimeKit;
import com.fysports.web.kit.commons.PathBizKit;
import com.fysports.web.kit.commons.StringKit;
import com.fysports.web.model.system.SystemUser;

import java.util.Map;


/**
 * Created by konbluesky
 * Date : 14-7-30 下午1:27
 * Project : JdmData_WebServer
 */
@Clear
public class LoginController extends AbstractBaseController {

    public void index() {
        render(PathBizKit.getPageAdminPath("/login.ftl"));
    }


    public void cklogin() {
        String uname = getPara("username");
        String upwd = getPara("password");
        String remember = getPara("remember");

        Map<String, Object> params = Maps.newHashMap();
        params.put("name", uname);
        params.put("pwd", MD5Kit.get32MD5(upwd));

        SystemUser su = SystemUser.dao.searchFirst(params);
        if (su != null) {
            setCookie(CookiesKit.COOKIES_AUTHMARK, CookiesKit.getCookieAuthToken(getRequest(), su),
                    DateTimeKit.time_day, "/");
            redirect("/main");
        }
        else {
            redirect("/login");
        }

    }


    public void logout() {
        removeCookie(CookiesKit.COOKIES_AUTHMARK);
        redirect("/login");
    }


    /**
     * 锁屏
     */
    public void lock() {
        String cookie = getCookie(CookiesKit.COOKIES_AUTHMARK);
        //防止从其他url进入lock页面
        if (StringKit.isBlank(cookie)) {
            cookie = getCookie(CookiesKit.COOKIES_LOCK);
        }
        //取出cookie中的useruuid
        CookiesKit.CookieVO cvo = CookiesKit.decodeCookieAuthToken(cookie);
        SystemUser su = SystemUser.dao.searchFirst("uuid", cvo.getUserid());
        setAttr("m", su);
        //设置lock cookie
        setCookie(CookiesKit.COOKIES_LOCK, cookie, DateTimeKit.time_day, "/");
        removeCookie(CookiesKit.COOKIES_AUTHMARK);
        render(PathBizKit.getPageAdminPath("plugins/lock.ftl"));
    }


    /**
     * 解锁
     */
    public void unlock() {
        String uname = getPara("username");
        String upwd = getPara("password");
        Map<String, Object> params = Maps.newHashMap();
        params.put("name", uname);
        params.put("pwd", MD5Kit.get32MD5(upwd));
        SystemUser su = SystemUser.dao.searchFirst(params);
        if (su != null) {
            //设回cookies
            setCookie(CookiesKit.COOKIES_AUTHMARK, getCookie(CookiesKit.COOKIES_LOCK), DateTimeKit.time_day,
                    "/");
            //删除lock的cookie
            removeCookie(CookiesKit.COOKIES_LOCK);
            redirect("/main");
        }
        else {
            redirect("/login/lock");
        }
    }

}
